/*
 * Zirco Browser for Android
 * 
 * Copyright (C) 2010 J. Devauchelle and contributors.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 3 as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

package com.gogowan.agroenterprise.utils;

import java.util.Date;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.provider.Browser;
import android.util.Log;

/**
 * 我的书签历史管理
 * @author zk
 *
 */
public class Histroy {
	
	/**
	 * 主页
	 */
	static final public String MAIN_PAGE="http://wap.188114.net"; 
	/**
	 * 关于码,暂不使用
	 * @deprecated
	 */
	public static final String ABOUT_ICODE = "99031500";

	/**
	 * 添加历史并跳转到浏览器
	 * @param activity 上下文对象
	 * @param icode i码
	 */
	public static void goICode(Activity activity,String format,String icode,boolean isPaima){		
		String uri=ICodeUtils.getServerURL(format,icode,isPaima); //转到新的页
		//Toast.makeText(activity, uri, Toast.LENGTH_LONG).show();
		addHistory(activity, icode, uri, Long.toString(new Date().getTime()));
		activity.startActivity(Utils.goUrl(uri));
	}
	
	/**
	 * 只添加历史，不跳转浏览器
	 * @param activity
	 * @param format
	 * @param icode
	 * @param isPaima
	 */
	public static void addUrlHistory(Context context,String url){		
		//String uri=ICodeUtils.getServerURL(format,icode,isPaima); //转到新的页
		addHistory(context, url, url, Long.toString(new Date().getTime()));
	}
	/**
	 * 如果没有就添加历史记录，如果有更新时间
	 * @param activity 上下文对象
	 * @param name 标题
	 * @param url 网址
	 * @param date 时间
	 */
	public static void addHistory(Context context, String name, String url,
			String date) {

		String time = "" + new Date().getTime();
		if (!date.equals(""))// 如果有数据，书签的最后访问时间与历史记录的一致
		{
			time = date;
		}
		// 增加历史记录
		ContentValues values = new ContentValues();
		values.put(DBHelper.NAME, name);
		values.put(DBHelper.URL, url);
		values.put(DBHelper.LASTDATE, time);
		ContentValues historyValues=fetchHistory(context, url);
		if(historyValues.size()>0)
		{
			values.put(DBHelper.COUNT, historyValues.getAsInteger(DBHelper.COUNT)+1);
			update(context, ""+historyValues.getAsLong(DBHelper.ID), values, DBHelper.HISTORY_TABLE_NAME);
		}else
		{
			values.put(DBHelper.DATE, time);
			values.put(DBHelper.COUNT, 1);
		    insert(context, values, DBHelper.HISTORY_TABLE_NAME);
		}

	}

	/**
	 * 保存历史到数据库
	 * @param activity 上下文对象
	 * @param values 
	 * @param table 数据库表名
	 */
	private static void insert(Context context, ContentValues values,
			String table) {
		try {
			// 创建DatabaseHelper对象
			DBHelper dbHelper = new DBHelper(context);
			// 得到一个可写的SQLiteDatabase对象
			SQLiteDatabase sqliteDatabase = dbHelper.getWritableDatabase();
			// 调用insert方法，就可以将数据插入到数据库当中
			// 第一个参数:表名称
			// 第二个参数：SQl不允许一个空列，如果ContentValues是空的，那么这一列被明确的指明为NULL值
			// 第三个参数：ContentValues对象
			sqliteDatabase.insert(table, null, values);
			sqliteDatabase.close();
			dbHelper.close();
			System.out.println("----------insert----------");
		} catch (SQLiteException e) {
			Log.d("e=", e.toString());
		}
	}
	/**更新历史
	 * @param id
	 * @param values
	 * @param table
	 * @return
	 */
	public static boolean update(Context activity,String id,ContentValues values,String table)
	{
		boolean isSuccess=false;
		try
		{
		// 创建一个DatabaseHelper对象
		DBHelper dbHelper = new DBHelper(activity);
		// 得到一个可写的SQLiteDatabase对象
		SQLiteDatabase sqliteDatabase = dbHelper.getWritableDatabase();
		// 创建一个ContentValues对象

		// 调用update方法
		// 第一个参数String：表名
		// 第二个参数ContentValues：ContentValues对象
		// 第三个参数String：where字句，相当于sql语句where后面的语句，？号是占位符
		// 第四个参数String[]：占位符的值
		isSuccess=sqliteDatabase.update(table, values, "id=?", new String[] {id})>0;
		sqliteDatabase.close();
		dbHelper.close();
		//System.out.println("-----------update------------");
		}
		catch (SQLiteException e) {
			Log.d("e=", e.toString());
		}
		return isSuccess;
	}

    /**根据url得到当天的历史ID
     * @param activity
     * @param uri
     * @return
     */
	public static ContentValues fetchHistory(Context activity, String uri) {
		MyLog ml=new MyLog(activity);
    	ml.writeSDCardLog("begin History.fetchHistory", "1");
		ContentValues values = new ContentValues();
		try {
			// 创建DatabaseHelper对象
			DBHelper dbHelper = new DBHelper(activity);
			// 得到一个只读的SQLiteDatabase对象
			SQLiteDatabase sqliteDatabase = dbHelper.getReadableDatabase();

			//Date lastDate = DateUtils.getDateAtMidnight(1);
			Date currentDate = DateUtils.getDateAtMidnight(0);
			Cursor cursor = sqliteDatabase.query(DBHelper.HISTORY_TABLE_NAME,
					new String[] { DBHelper.ID, DBHelper.COUNT}, " " 
					        //+ DBHelper.LASTDATE+ " <= " + lastDate.getTime() + "  AND " + " "
							+ DBHelper.LASTDATE + " > " + currentDate.getTime()
							+ " AND " + " " + DBHelper.URL + "='" + uri + "'",
					null, null, null, DBHelper.LASTDATE + " DESC");
			
			if (cursor.moveToFirst()) {
				// do {
				long id = cursor.getLong(cursor.getColumnIndex(DBHelper.ID));
				int count=cursor.getInt(cursor.getColumnIndex(DBHelper.COUNT));
				values.put(DBHelper.ID, id);
				values.put(DBHelper.COUNT, count);
				// } while (cursor.moveToNext());
			}

			cursor.close();
			sqliteDatabase.close();
			dbHelper.close();
			ml.writeSDCardLog("end History.fetchHistory", "1");
			return values;
		} catch (SQLiteException e) {
			Log.d("e=", e.toString());
		}
		ml.writeSDCardLog("end History.fetchHistory", "1");
		return values;
	}

}
